package com.zeji.androidadvance.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.style.ImageSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class CenterImageSpan extends ImageSpan {
    public CenterImageSpan(@NonNull Context context, @NonNull Bitmap bitmap) {
        super(context, bitmap);
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        int fontHeight = paint.getFontMetricsInt().descent - paint.getFontMetricsInt().ascent;
        int imageHeight = getDrawable().getBounds().height();
        if (fm != null) {
            fm.ascent = (int) (paint.getFontMetricsInt().ascent - ((imageHeight - fontHeight) / 2.0f));
            fm.top = fm.ascent;
            fm.descent = fm.ascent + imageHeight;
            fm.bottom = fm.descent;
        }
        return getDrawable().getBounds().right;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        int fontHeight = paint.getFontMetricsInt().descent - paint.getFontMetricsInt().ascent;
        int imageAscent = (int) (paint.getFontMetricsInt().ascent - ((getDrawable().getBounds().height() - fontHeight) / 2.0f));
        canvas.save();
        canvas.translate(x, (y + imageAscent));
        getDrawable().draw(canvas);
        canvas.restore();
    }
}
